# -*- coding: utf-8 -*-
# @Date     : 2021/4/9 15:25
# @Author   : xiaochuang.wu
# @File     : sign_body_args.py

import json, hashlib


def sign(body: dict, args: dict) -> str:
    if "sign" in body:
        body.pop("sign")
    print(f"cal sign by body: {body}, args: {args}")

    body = {k: body[k] for k in sorted(body)}  # 对键值对排序（顺序）
    body = json.dumps(body, separators=(',', ':'), ensure_ascii=False)  # 转JSON字符串。不允许,和:后有空格
    args['body'] = body
    args = {k: args[k] for k in sorted(args)}  # 对键值对排序（顺序）
    sign = '&'.join(['{0}={1}'.format(k, v) for k, v in args.items()])  # 拼接签名字符串
    sign = hashlib.md5(sign.encode('utf-8')).hexdigest()  # md5算法
    return sign


if __name__ == '__main__':
    body = {"appid": "80773369", "app_secret": "df62477c8c164be48e9a18ba90825c24", "sign": "test"}

    args = {"timestamp": ['1617955678']}
    print(sign(body, args))